package com.czwj.service.impl;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.czwj.dao.CompanyMapper;
import com.czwj.dao.DepartmentMapper;
import com.czwj.dao.JobberMapper;
import com.czwj.dao.LevelMapper;
import com.czwj.dao.RoleMapper;
import com.czwj.dao.UserInfoMapper;
import com.czwj.entities.Jobber;
import com.czwj.entities.UserInfo;
import com.czwj.service.UserInfoService;
import com.czwj.util.CipherUtil;

@Service
public class UserInfoServiceImpl implements UserInfoService{
	@Resource
	UserInfoMapper mapper;
	
	@Resource
	JobberMapper jmapper;
	
	@Resource
	CompanyMapper companyMapper;
	
	@Resource
	DepartmentMapper departmentMapper;
	
	@Resource
	RoleMapper roleMapper;
	
	@Resource
	LevelMapper levelMapper;
	
	private final static String XLS = "xls";
	
	private final static String XLSX = "xlsx";
	
	@Transactional
	public Integer importExcel(MultipartFile myFile,HttpServletRequest request) throws Exception{
		Workbook workbook = null;
		String fileName = myFile.getOriginalFilename();
		if(fileName.endsWith(XLS)){
			workbook = new HSSFWorkbook(myFile.getInputStream());
		}else if(fileName.endsWith(XLSX)){
			workbook = new XSSFWorkbook(myFile.getInputStream());
		}else{
			throw new Exception("不是Excel文件");
		}
		Sheet sheet = workbook.getSheet("Sheet1");
		int rows = sheet.getLastRowNum();
		if(rows == 0){
			throw new Exception("请填写数据");
		}
		for(int i = 1;i <= rows;i++){
			Row row = sheet.getRow(i);
			if(row != null){
				UserInfo userInfo = new UserInfo();
				String username = getCellValue(row.getCell(0));
				UserInfo user = this.mapper.findByUserName(username);
				if(user != null){
					continue;
				}else{
					userInfo.setUsername(username);
				}
				userInfo.setPassword(CipherUtil.encrypt(username));
				String name = getCellValue(row.getCell(1));
				userInfo.setName(name);
				String idcard = getCellValue(row.getCell(2));
				userInfo.setIdcard(idcard);
				String sex = getCellValue(row.getCell(3));
				userInfo.setSex(sex);
				String jobno = getCellValue(row.getCell(4));
				userInfo.setJobno(jobno);
				String mobile = getCellValue(row.getCell(5));
				userInfo.setMobile(mobile);
				String departmentname = getCellValue(row.getCell(6));
				Integer departmentid = departmentMapper.findByName(departmentname).getId();
				userInfo.setDepartmentid(departmentid);
				String levelname = getCellValue(row.getCell(7));
				Integer levelid = levelMapper.findByName(levelname).getId();
				userInfo.setLevelid(levelid);
				String rolename = getCellValue(row.getCell(8));
				Integer roleid = roleMapper.findByName(rolename).getId();
				userInfo.setRoleid(roleid);
				Subject currentUser = SecurityUtils.getSubject();
				UserInfo u = (UserInfo)currentUser.getSession().getAttribute("userInfo");
				userInfo.setCompanyid(u.getCompanyid());
				userInfo.setStatus(2);
				userInfo.setCreaterid(u.getId());
				userInfo.setCreatedate(new Date());
				userInfo.setCreateip(request.getRemoteAddr());
				mapper.insertSelective(userInfo);
			}
		}
		return rows - 1;
	}
	
	private String getCellValue(Cell cell){
		// TODO Auto-generated method stub
		String value = "";
		if(cell != null){
			switch(cell.getCellType()){
				case HSSFCell.CELL_TYPE_NUMERIC:// 数字
					value = cell.getNumericCellValue() + "";
					if(HSSFDateUtil.isCellDateFormatted(cell)){
						Date date = cell.getDateCellValue();
						if(date != null){
							value = new SimpleDateFormat("yyyy-MM-dd").format(date);
						}else{
							value = "";
						}
					}else{
						value = new DecimalFormat("0").format(cell.getNumericCellValue());
					}
					break;
				case HSSFCell.CELL_TYPE_STRING:
					value = cell.getStringCellValue();
					break;
				case HSSFCell.CELL_TYPE_BOOLEAN:
					value = cell.getBooleanCellValue() + "";
					break;
				case HSSFCell.CELL_TYPE_FORMULA:// 公式
					value = cell.getCellFormula() + "";
					break;
				case HSSFCell.CELL_TYPE_BLANK:// 空值
					value = "";
					break;
				case HSSFCell.CELL_TYPE_ERROR:
					value = "非法字符";
					break;
				default:
					value = "未知类型";
					break;
			}
		}
		return value.trim();
	}
	
	@Override
	public UserInfo findByUserName(String username){
		// TODO Auto-generated method stub
		return this.mapper.findByUserName(username);
	}
	
	@Override
	public int update(UserInfo user){
		// TODO Auto-generated method stub
		return this.mapper.updateByPrimaryKeySelective(user);
	}
	
	@Override
	public int insert(UserInfo user){
		// TODO Auto-generated method stub
		return this.mapper.insertSelective(user);
	}
	
	@Override
	public int delete(int id){
		// TODO Auto-generated method stub
		return this.mapper.deleteByPrimaryKey(id);
	}
	
	@Override
	public List<UserInfo> search(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.search(map);
	}
	
	@Override
	public int count(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.count(map);
	}
	
	@Override
	public List<UserInfo> level(Map<String,Object> params){
		// TODO Auto-generated method stub
		return this.mapper.level(params);
	}
	
	@Override
	public UserInfo searchbymobile(String mobile){
		// TODO Auto-generated method stub
		return this.mapper.searchbymobile(mobile);
	}
	
	@Override
	public int updateStatus(Map<String,Object> map){
		// TODO Auto-generated method stub
		return this.mapper.updateStatus(map);
	}
	
	@Override
	public UserInfo selectByPrimaryKey(int userid){
		// TODO Auto-generated method stub
		return this.mapper.selectByPrimaryKey(userid);
	}
	
	@Override
	public List<UserInfo> selectbycompanyrole(int companyid){
		// TODO Auto-generated method stub
		return mapper.selectbycompanyrole(companyid);
	}
	
	/** 
	* 
	* @param companyid
	* @return
	* @see com.czwj.service.UserInfoService#selectbycompany(int)
	*/
	@Override
	public List<UserInfo> selectbycompany(int companyid){
		// TODO Auto-generated method stub
		return this.mapper.selectbycompany(companyid);
	}
	
	/** 
	* 
	* @param params
	* @return
	* @see com.czwj.service.UserInfoService#duty3(java.util.Map)
	*/
	@Override
	public List<UserInfo> duty3(Map<String,Object> params){
		// TODO Auto-generated method stub
		return this.mapper.duty3(params);
	}
	
	/** 
	* 
	* @param name
	* @param jobno
	* @param idcard
	* @param sex
	* @param mobile
	* @param companyid
	* @param departmentid
	* @param projectitemid
	* @param projectitemchildid
	* @param salary
	* @return
	* @see com.czwj.service.UserInfoService#insertjobber(java.lang.String, java.lang.String, java.lang.String, java.lang.Integer, java.lang.String, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.Integer, java.lang.String)
	*/
	@Transactional
	@Override
	public int insertjobber(String name,String jobno,String idcard,String sex,String mobile,Integer companyid,
			Integer departmentid,Integer createrid,String createip,Integer projectitemid,Integer projectitemchildid,
			String salary){
		// TODO Auto-generated method stub
		int count = 0;
		UserInfo userInfo = new UserInfo(name,jobno,idcard,sex,mobile,companyid,departmentid,createrid,createip,
				new Date(),2);
		count += this.mapper.insertSelective(userInfo);
		Jobber jobber = new Jobber();
		jobber.setProjectitemchildid(projectitemchildid);
		jobber.setProjectitemid(projectitemid);
		jobber.setUserid(userInfo.getId());
		jobber.setSalary(salary);
		count += jmapper.insertSelective(jobber);
		return count;
	}

	/** 
	* 
	* @param companyid
	* @return
	* @see com.czwj.service.UserInfoService#selectbycompanyroleid(java.lang.Integer)
	*/
	@Override
	public List<UserInfo> selectbycompanyroleid(Integer companyid){
		// TODO Auto-generated method stub
		return this.mapper.selectbycompanyroleid(companyid);
	}
}
